package com.cpkf.util.iTextPDF;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Data convert util
 *
 * @author Hyman Hu
 * @since  2014-6-26
 * Copyright SHOP.COM: all rights reserved worldwide
 */
public class DataConvertUtil {
	
	/**
	 * convert ResultSet to List
	 * 
	 * @param rs                            	this is return from db query
	 * @return List<Map<String, Object>>    	map<key, value> object is corresponding to each line of ResultSet, 
	 * 											key is column name, value is column value, list contain all lines of ResultSet
	 * @throws SQLException
	 */
	public static List<Map<String, Object>> convertToList(ResultSet rs) throws SQLException {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		Map<String, Object> recordMap = null;

		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();

		while (rs.next()) {
			recordMap = new TreeMap<String, Object>();
			for (int i = 1; i <= columnCount; i++) {
				recordMap.put(rsmd.getColumnName(i), rs.getObject(i));
			}
			result.add(recordMap);
		}

		return result;
	}

	/**
	 * convert ResultSet to JSONArray
	 * 
	 * @param rs					this is return from db query
	 * @return JSONArray			JSONArray contain JSONObjects, the JSONObject is corresponding to each line of ResultSet
	 * @throws SQLException
	 * @throws JSONException
	 */
	public static JSONArray convertToJSONArray(ResultSet rs) throws SQLException, JSONException {
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = null;

		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();

		while (rs.next()) {
			jsonObject = new JSONObject();
			for (int i = 1; i <= columnCount; i++) {
				jsonObject.put(rsmd.getColumnName(i), rs.getObject(i));
			}
			jsonArray.put(jsonObject);
		}

		return jsonArray;
	}
	
	/**
	 * convert JSONArray string to JSONArray
	 * 
	 * @param source			JSONArray string
	 * @return JSONArray		JSONArray contain JSONObjects
	 */
	public static JSONArray convertToJSONArray(String source) {
		JSONArray jsonArray = null;
		try {
			jsonArray = new JSONArray(source);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonArray;
	}
	
}
